package com.bing.bingPro.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bing.bingPro.entity.TestStatusEntity;
import com.bing.bingPro.mapper.TestStatusMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class ProTerminalTestExportService {
    private final TestStatusMapper testStatusMapper;

    public ProTerminalTestExportService(TestStatusMapper testStatusMapper) {
        this.testStatusMapper = testStatusMapper;
    }

    private static final String PROVINCE = "province";
    private static final String RESULT = "result";
    private static final String CONTENT_TYPE = "application/vnd.ms-excel;charset=utf-8";
    private static final String HEADER1 = "Content-Disposition";
    private static final String HEADER2 = "attachment;filename=";
    private static final String HEADER3 = "UTF-8";
    private static final String CLOSEERR = "关闭流异常";
    private static final String VENDOR = "vendor";
    private static final String SHAPE = "shape";
    private static final String GATEHRAD = "网关硬件版本";
    private static final String GATEHRADE = "gateway_hardware_version";
    private static final String CPUMODEL = "cpu_model";
    private static final String GATEMODEL = "gateway_model";
    private static final String CHIPFACTORY = "chip_factory";
    private static final String WIFICHIPFAC = "wifi_chip_factory";
    private static final String CPUT = "CPU型号";
    private static final String WIFIVC = "WiFi芯片厂家";
    private static final String WIFIVM = "WiFi芯片型号";
    private static final String WCM = "wifi_chip_model";
    private static final String RAM = "ram_model";
    private static final String FOUNDRY = "foundry";

    /**
     * 导出提测数据到前端
     **/
    public void submitTestExport(HttpServletResponse response, List<Map<String,Object>> datalist, String year) throws IOException {

        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<Map<String,Object>> excelMapList = Lists.newArrayList();
        for(Map<String,Object> map: datalist){
            Map<String,Object> exclMap = new LinkedHashMap<>();
            exclMap.put("序号",map.get("id"));
            exclMap.put("厂商",map.get(VENDOR));
            exclMap.put("形态",map.get(SHAPE));
            exclMap.put("类型",map.get("type"));
            exclMap.put("网关型号",map.get(GATEMODEL));
            exclMap.put(GATEHRAD,map.get(GATEHRADE));
            exclMap.put("代工厂",map.get(FOUNDRY));
            exclMap.put("芯片厂家",map.get(CHIPFACTORY));
            exclMap.put(CPUT,map.get(CPUMODEL));
            exclMap.put(WIFIVC,map.get(WIFICHIPFAC));
            exclMap.put(WIFIVM,map.get(WCM));
            exclMap.put("内存型号",map.get(RAM));
            exclMap.put("省份",map.get(PROVINCE));
            switch (year) {
                case "2021":
                    exclMap.put("21年统一软件版本", map.get("t2021_version"));
                    exclMap.put("21年提测结果", map.get("t2021_result"));
                    exclMap.put("21年提测时间", map.get("t2021_test_timestamp"));
                    exclMap.put("21年版本省内是否可部署", map.get("t2021_allow_deploy"));
                    break;
                case "2022":
                    exclMap.put("22年统一软件版本", map.get("t2022_version"));
                    exclMap.put("22年提测结果", map.get("t2022_result"));
                    exclMap.put("22年提测时间", map.get("t2022_test_timestamp"));
                    exclMap.put("22年版本省内是否可部署", map.get("t2022_allow_deploy"));
                    break;
                case "2023":
                    exclMap.put("23年统一软件版本", map.get("t2023_version"));
                    exclMap.put("23年提测结果", map.get("t2023_result"));
                    exclMap.put("23年提测时间", map.get("t2023_test_timestamp"));
                    exclMap.put("23年版本省内是否可部署", map.get("t2023_allow_deploy"));
                    break;
                default:break;
            }
            exclMap.put("移动测试负责人",map.get("cm_test_contact"));
            exclMap.put("移动测试负责人联系电话",map.get("cm_contact_mobile"));
            exclMap.put("OA联系邮箱",map.get("cm_contact_mailbox"));
            exclMap.put("厂商接口人",map.get("vd_contact"));
            exclMap.put("厂商接口人联系电话",map.get("vd_contact_mobile"));
            exclMap.put("邮箱",map.get("vd_contact_mailbox"));
            excelMapList.add(exclMap);
        }
        writer.write(excelMapList, true);
        writer.autoSizeColumnAll();
        exportWriter(writer,String.format("%s 年省级终端版本提测表", year),response);
    }

    /**
     * 导出提测数据-全量
     **/
    public void submitTestAllExport(HttpServletResponse response, List<Map<String,Object>> datalist) throws IOException {

        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<Map<String,Object>> excelMapList = Lists.newArrayList();
        for(Map<String,Object> map: datalist){
            Map<String,Object> exclMap = new LinkedHashMap<>();
            exclMap.put("序号",map.get("id"));
            exclMap.put("厂商",map.get(VENDOR));
            exclMap.put("形态",map.get(SHAPE));
            exclMap.put("类型",map.get("type"));
            exclMap.put("网关型号",map.get(GATEMODEL));
            exclMap.put(GATEHRAD,map.get(GATEHRADE));
            exclMap.put("代工厂",map.get(FOUNDRY));
            exclMap.put("芯片厂家",map.get(CHIPFACTORY));
            exclMap.put(CPUT,map.get(CPUMODEL));
            exclMap.put(WIFIVC,map.get(WIFICHIPFAC));
            exclMap.put(WIFIVM,map.get(WCM));
            exclMap.put("内存大小",map.get(RAM));
            exclMap.put("省份",map.get(PROVINCE));
            exclMap.put("21年统一软件版本", map.get("t2021_version"));
            exclMap.put("21年提测结果", map.get("t2021_result"));
            exclMap.put("21年提测时间", map.get("t2021_test_timestamp"));
            exclMap.put("21年测试未通过项", map.get("t2021_failed_items"));
            exclMap.put("21年测试未通过项个数", map.get("t2021_failed_items_num"));
            exclMap.put("21年结果由通过变更为不通过", map.get("t2021_pass_to_fail_flag"));
            exclMap.put("21年版本全国测试通过率", map.get("t2021_total_pass_rate"));
            exclMap.put("21年版本省内是否可部署", map.get("t2021_allow_deploy"));
            exclMap.put("22年统一软件版本", map.get("t2022_version"));
            exclMap.put("22年提测结果", map.get("t2022_result"));
            exclMap.put("22年提测时间", map.get("t2022_test_timestamp"));
            exclMap.put("22年测试未通过项", map.get("t2022_failed_items"));
            exclMap.put("22年测试未通过项个数", map.get("t2022_failed_items_num"));
            exclMap.put("22年结果由通过变更为不通过", map.get("t2022_pass_to_fail_flag"));
            exclMap.put("22年版本全国测试通过率", map.get("t2022_total_pass_rate"));
            exclMap.put("22年版本省内是否可部署", map.get("t2022_allow_deploy"));
            exclMap.put("23年统一软件版本", map.get("t2023_version"));
            exclMap.put("23年提测结果", map.get("t2023_result"));
            exclMap.put("23年提测时间", map.get("t2023_test_timestamp"));
            exclMap.put("23年测试未通过项", map.get("t2023_failed_items"));
            exclMap.put("23年测试未通过项个数", map.get("t2023_failed_items_num"));
            exclMap.put("23年结果由通过变更为不通过", map.get("t2023_pass_to_fail_flag"));
            exclMap.put("23年版本全国测试通过率", map.get("t2023_total_pass_rate"));
            exclMap.put("23年版本省内是否可部署", map.get("t2023_allow_deploy"));
            exclMap.put("移动测试负责人",map.get("cm_test_contact"));
            exclMap.put("移动测试负责人联系电话",map.get("cm_contact_mobile"));
            exclMap.put("OA联系邮箱",map.get("cm_contact_mailbox"));
            exclMap.put("厂商接口人",map.get("vd_contact"));
            exclMap.put("厂商接口人联系电话",map.get("vd_contact_mobile"));
            exclMap.put("邮箱",map.get("vd_contact_mailbox"));
            excelMapList.add(exclMap);
        }
        writer.write(excelMapList, true);
        writer.autoSizeColumnAll();
        exportWriter(writer,"省级终端版本提测全量数据表",response);
    }

    // 下载测试明细
    public Map<String, Object> downloadDetailTableFunc(HttpServletResponse response, Long[] ids, String year) throws IOException {
        Map<String, Object> mapResult = new HashMap<>();
        for (Long id : ids) {
            TestStatusEntity idsDbObj;
            idsDbObj = testStatusMapper.findOne(testStatusMapper.query().where.relatedId().eq(id).
                    and.fileinfopath().notNull().and.year().eq(year).end().orderBy().testTimestamp().desc().end().limit(1));
            if (Objects.isNull(idsDbObj)) {
                mapResult.put(RESULT, "下载失败！该条目无流转状态或没有上传测试明细！！");
                return mapResult;
            }
            if (Objects.nonNull(idsDbObj.getFileinfopath()) && !idsDbObj.getFileinfopath().isEmpty()) {
                try {
                    ServletOutputStream out = null;
                    String fileName = FilenameUtils.getName(idsDbObj.getFileinfopath());

                    //response为HttpServletResponse对象
                    response.setContentType(CONTENT_TYPE);
                    response.setHeader(HEADER1, HEADER2 + java.net.URLEncoder.encode(fileName, HEADER3));
                    out = response.getOutputStream();
                    try (FileInputStream ips = new FileInputStream(idsDbObj.getFileinfopath()))  {
                        //读取文件流
                        int len = 0;
                        byte[] buffer = new byte[1024 * 10];
                        while ((len = ips.read(buffer)) != -1) {
                            out.write(buffer, 0, len);
                        }
                        out.flush();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        mapResult.put(RESULT, "下载成功！");
        return mapResult;
    }
    // 下载测试用例模版
    public void downloadDetailStencilFunc(HttpServletResponse response){
        TestStatusEntity idsDbObj;
        idsDbObj = testStatusMapper.findOne(testStatusMapper.query().where.opinion().eq("模版下载").end());
        if (Objects.nonNull(idsDbObj.getFileinfopath()) && !idsDbObj.getFileinfopath().isEmpty()) {
            try (ServletOutputStream out =response.getOutputStream()) {
                String fileName = FilenameUtils.getName(idsDbObj.getFileinfopath());
                response.setContentType(CONTENT_TYPE);
                response.setHeader(HEADER1, HEADER2 + java.net.URLEncoder.encode(fileName, HEADER3));
                try (FileInputStream ips = new FileInputStream(idsDbObj.getFileinfopath()))  {
                    //读取文件流
                    int len = 0;
                    byte[] buffer = new byte[1024 * 10];
                    while ((len = ips.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.error("提测模版下载失败！");
        }
    }
    private void exportWriter(ExcelWriter writer, String excelName, HttpServletResponse response) throws IOException {
        //response为HttpServletResponse对象
        response.setContentType(CONTENT_TYPE);
        response.setHeader(HEADER1, HEADER2 + java.net.URLEncoder.encode(excelName, HEADER3) + ".xlsx");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}
